
from django.shortcuts import render, HttpResponse, redirect

from book01 import models
from book01.forms import Author_Form, RegForm, Publisher_Form, Book_Form


# Create your views here.
def index(request):
    return HttpResponse("删除、修改，查询未写，大同小异")


# 用户注册
def RegForm_view(request):
    User_Form = RegForm()
    if request.method == "POST":
        User_Form = RegForm(request.POST)
        if User_Form.is_valid():
            data = User_Form.cleaned_data
            username = data.get('username')
            password = data.get('password')
            email = data.get('email')
            phone = data.get('phone')
            models.Userinfo.objects.create(username=username,password=password,email=email,phone=phone)
            return redirect('RegForm_view')

    return render(request, "book01/regedit.html", {"User_Form": User_Form})


# 添加作者信息
def Author_info(request):
    author_form = Author_Form()
    if request.method == "POST":
        author_form = Author_Form(request.POST)
        if author_form.is_valid():
            data = author_form.cleaned_data
            temp = models.Author.objects.create(**data)
            temp.save()
            author_form = Author_Form()
            return render(request, 'book01/author_info.html', {'Author_Form': author_form, 'msg': '添加成功'})
    return render(request, 'book01/author_info.html', {'Author_Form': author_form})


# 添加出版社信息
def Publisher_info(request):
    publisher_form = Publisher_Form()
    if request.method == "POST":
        publisher_form = Publisher_Form(request.POST)
        if publisher_form.is_valid():
            data = publisher_form.cleaned_data
            temp = models.Publisher.objects.create(**data)
            temp.save()
            publisher_form = Publisher_Form()
            return render(request, 'book01/author_info.html', {'Publisher_Form': publisher_form, 'msg': '添加成功'})
    return render(request, 'book01/publisher_info.html', {'Publisher_Form': publisher_form})


# 添加图书信息
def Book_info(request):
    book_form = Book_Form()
    if request.method == "POST":
        book_form = Book_Form(request.POST)
        if book_form.is_valid():
            # 因为有外键关联，所以要一个一个写入
            data = book_form.cleaned_data
            author = data.get('author')
            title = data.get('title')
            date = data.get('date')
            publisher = data.get('publisher')
            models.Book.objects.create(title=title,date=date,author_id=author,publisher_id=publisher)
            return redirect('book_info')
    return render(request, 'book01/book_info.html', {'Book_Form': book_form})
